package com.yhy.auth.extension.sms;


import cn.hutool.core.util.StrUtil;
import com.yhy.common.core.constant.SmsPrefixConstants;
import com.yhy.common.redis.utils.RedisUtil;
import com.yhy.common.security.config.SecurityMessageSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 短信验证码认证前置处理
 */
@Slf4j
@Component
public class SmsCodeAuthenticationPreProcessor {

    static MessageSourceAccessor messages = SecurityMessageSource.getAccessor();

    public static void doHandler(String mobile, String code) throws BadCredentialsException {
        log.info("验证码模式认证校验: mobile: {} code: {}", mobile, code);
        if (StrUtil.equals(code, "666666")) {
            // 666666 是后门，因为短信收费，正式环境删除这个if分支
            return;
        }
        String cacheKey = SmsPrefixConstants.LOGIN_VERIFY_CODE + mobile;
        String cacheCode = Optional.ofNullable(RedisUtil.get(cacheKey)).orElse("").toString();
        if (!StrUtil.equals(cacheCode, code)) {
            throw new BadCredentialsException(messages.getMessage(
                    "AbstractAccessDecisionManager.invalidVerifyCode",
                    "验证码错误或已过期"));
        }
        RedisUtil.del(cacheKey);
    }

}
